package someTestExcemple.thread;

import lombok.Data;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
public class AccountLock {
    private static String cardId;
    private double moneyLock;
    private final Lock lock = new ReentrantLock();

    public AccountLock(String cardId, double money) {
        this.cardId = cardId;
        this.moneyLock = money;
    }

    public AccountLock() {
    }
    //3.使用显示的lock锁来保证线程安全
    public void drawAmount(double drawAmount) {
        try {
            lock.lock(); //加锁
            System.out.println(Thread.currentThread().getName() + "取钱线程启动...当前余额:" + this.moneyLock);
            if (this.moneyLock >= drawAmount) {
                System.out.println(Thread.currentThread().getName() + "取钱成功，吐出钞票：" + drawAmount);
                this.moneyLock -= drawAmount;
                System.out.println(Thread.currentThread().getName() + "账户余额为：" + this.moneyLock);
            } else {
                System.out.println(Thread.currentThread().getName() + "只有" + this.moneyLock + "元。取钱失败，账户余额不足!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock(); //释放锁 --无论前面出现什么异常这个锁都要释放
        }

    }
}
